package com.loan.market.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.google.gson.reflect.TypeToken
import com.loan.market.R
import com.loan.market.base.BaseBindingActivity
import com.loan.market.bean.City
import com.loan.market.bean.UserInfo
import com.loan.market.databinding.ActivityEditInfoBinding
import com.loan.market.databinding.LayoutAddressBinding
import com.loan.market.databinding.LayoutBirthBinding
import com.loan.market.event.SaveInfoEvent
import com.loan.market.http.ApiService
import com.loan.market.http.getHttpMap
import com.loan.market.http.request
import com.loan.market.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.Locale

class EditInfoActivity : BaseBindingActivity<ActivityEditInfoBinding>(), OnClickListener {

    override fun getViewBinding(): ActivityEditInfoBinding {
        return ActivityEditInfoBinding.inflate(layoutInflater)
    }

    private val genders = arrayListOf("M", "F", "X")
    private val maritalArray by lazy { resources.getStringArray(R.array.marital) }

    override fun initUi(savedInstanceState: Bundle?) {
    }

    override fun initEvent() {
        binding.tvName.setOnClickListener(this)
        binding.tvBirth.setOnClickListener(this)
        binding.tvSex.setOnClickListener(this)
        binding.tvEdu.setOnClickListener(this)
        binding.tvWork.setOnClickListener(this)
        binding.tvMarital.setOnClickListener(this)
        binding.tvAddress.setOnClickListener(this)
        binding.btnSave.setOnClickListener(this)
    }

    private val cities = arrayListOf<City>()

    private var userInfo = UserInfo()

    override fun initData() {
        http {
            withContext(Dispatchers.IO) {
                val list = readJson()
                cities.addAll(list)
            }
        }
        http(onFinish = ::dismissLoading) {
            showLoading()
            val map = getHttpMap(501)
            request<UserInfo>(map, ApiService.path4)?.let {
                userInfo = it
                binding.tvName.setRightText(userInfo.name)
                binding.tvBirth.setRightText(userInfo.birthDate)
                binding.tvSex.setRightText(genders.getOrNull(userInfo.gender - 1))
                binding.tvEdu.setRightText(edus.find { it.first == userInfo.education }?.second)
                binding.tvWork.setRightText(works.find { it.first == userInfo.workIndustry }?.second)
                binding.tvMarital.setRightText(maritalArray.getOrNull(userInfo.marital - 1))
                binding.tvAddress.setRightText(userInfo.addressProvince + " " + userInfo.addressCity)
            }
        }
    }

    override fun onClick(v: View) {
        when (v) {
            binding.tvName -> {
                startResult(binding.tvName.id, Intent(this, EditNameActivity::class.java)) {
                    if (it != RESULT_OK) return@startResult
                    binding.tvName.setRightText(this?.getStringExtra("name"))
                    userInfo.name = this?.getStringExtra("name") ?: ""
                }
            }

            binding.tvBirth -> {
                val bind = LayoutBirthBinding.inflate(layoutInflater)
                bind.picker.setCustomLocale(Locale("es", "ar"))
                val dialog = showDialog(bind.root, fillWidth = true, position = Gravity.BOTTOM)
                bind.btnConfirm.setOnClickListener {
                    val startTemp = bind.picker.date.time
                    if (startTemp > System.currentTimeMillis()) {
                        showToast("la fecha inicio debe ser anterior a la actual")
                        return@setOnClickListener
                    }
                    dialog.dismiss()
                    binding.tvBirth.setRightText(startTemp.formatTime())
                    userInfo.birthDate = startTemp.formatTime()
                }
            }

            binding.tvSex -> {
                showSheet(genders) {
                    binding.tvSex.setRightText(this)
                    userInfo.gender = it + 1
                }
            }

            binding.tvEdu -> {
                showSheet(edus.map { it.second }) {
                    binding.tvEdu.setRightText(this)
                    userInfo.education = edus[it].first
                }
            }

            binding.tvWork -> {
                showSheet(works.map { it.second }) {
                    binding.tvWork.setRightText(this)
                    userInfo.workIndustry = works[it].first
                }
            }

            binding.tvMarital -> {
                showSheet(maritalArray.toList()) {
                    binding.tvMarital.setRightText(this)
                    userInfo.marital = it + 1
                }
            }

            binding.tvAddress -> {
                var province = ""
                var first = true
                val bind = LayoutAddressBinding.inflate(layoutInflater)
                val dialog = showDialog(bind.root, fillWidth = true, position = Gravity.BOTTOM)
                bind.rvCity.adapter = cityAdapter
                cityAdapter.submitList(cities.map { it.name }.distinct())
                cityAdapter.addOnItemChildClickListener(R.id.tv_city) { adapter, view, position ->
                    if (first) {
                        first = false
                        bind.rvCity.scroll(0)
                        cityAdapter.submitList(cities[position].children.map { it.name }.distinct())
                        province = cities[position].name
                    } else {
                        dialog.dismiss()
                        userInfo.addressProvince = province
                        userInfo.addressCity = cityAdapter.getItem(position) ?: ""
                        binding.tvAddress.setRightText(province + " " + cityAdapter.getItem(position))
                    }
                }
                bind.slideBar.setOnTouchLetterChangeListener { letter ->
                    val index = cityAdapter.items.indexOfFirst {
                        it[0].toString().equals(letter, true)
                    }
                    if (index >= 0) {
                        bind.rvCity.scroll(index)
                    } else if (letter == "#") {
                        bind.rvCity.scroll(0)
                    }
                }
            }

            binding.btnSave -> {
                http(onFinish = {
                    dismissLoading()
                }) {
                    showLoading()
                    val map = getHttpMap(502)
                    map["name"] = userInfo.name
                    map["birthDate"] = userInfo.birthDate
                    map["gender"] = userInfo.gender
                    map["education"] = userInfo.education
                    map["workIndustry"] = userInfo.workIndustry
                    map["marital"] = userInfo.marital
                    map["addressProvince"] = userInfo.addressProvince
                    map["addressCity"] = userInfo.addressCity
                    request<Any>(map, ApiService.path4)
                    EventBus.getDefault().post(SaveInfoEvent(userInfo.name))
                    finish()
                }
            }
        }
    }

    private val cityAdapter by lazy {
        object : BaseQuickAdapter<String, QuickViewHolder>() {
            override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: String?) {
                if (holder.layoutPosition == 0 || items[holder.layoutPosition][0] != items[holder.layoutPosition - 1][0]) {
                    holder.setVisible(R.id.tv_first, true)
                } else {
                    holder.setGone(R.id.tv_first, true)
                }
                holder.setText(R.id.tv_first, item?.get(0).toString())
                holder.setText(R.id.tv_city, item)
            }

            override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
                return QuickViewHolder(R.layout.item_city, parent)
            }
        }
    }

    private fun readJson(): ArrayList<City> {
        val inputStream = resources.assets.open("code.json")
        val bufferedReader = BufferedReader(InputStreamReader(inputStream))
        val type = object : TypeToken<ArrayList<City>>() {}.type
        return GsonUtil.getInstance().fromJson(bufferedReader.use(BufferedReader::readText), type)
    }
}

val edus = listOf(
    1 to "Primaria",
    2 to "Secundaria",
    6 to "Universidad titulado",
    7 to "Maestria/Doctorado"
)

val works = listOf(
    "A" to "Agricultura, silvicultura, ganadería y pesca",
    "B" to "Minería",
    "C" to "Manufactura",
    "D" to "Producción y suministro de electricidad, gas y agua",
    "E" to "Construcción",
    "F" to "Transporte, almacenamiento y servicios postales",
    "G" to "Transmisión de información, software y servicios tecnológicos",
    "H" to "Mayoristas y minoristas",
    "I" to "Alojamiento y servicios de comida",
    "J" to "Finanzas",
    "K" to "Bienes raíces",
    "L" to "Alquiler y servicios empresariales",
    "M" to "Investigación científica y servicios técnicos",
    "N" to "Gestión del agua, medio ambiente e instalaciones públicas",
    "O" to "Servicios para residentes, reparaciones y otros servicios",
    "P" to "Educación",
    "Q" to "Sanidad y trabajo social",
    "R" to "Cultura, deportes y entretenimiento",
    "S" to "Administración pública, seguridad social y organizaciones sociales",
    "T" to "Organizaciones internacionales",
    "no" to "Desempleado"
)